package com.bigtotoro.shuiyincamera.image;

import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.RectF;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigtotoro.shuiyincamera.BaseActivity;
import com.bigtotoro.shuiyincamera.MyArtListActivity;
import com.bigtotoro.shuiyincamera.R;
import com.bigtotoro.shuiyincamera.ShowMyArtsActivity;
import com.bigtotoro.shuiyincamera.editimage.view.imagezoom.ImageViewTouchBase;
import com.bigtotoro.shuiyincamera.model.MyArt;
import com.bigtotoro.shuiyincamera.editimage.EditImageActivity;
import com.bigtotoro.shuiyincamera.editimage.utils.BitmapUtils;
import com.bigtotoro.shuiyincamera.editimage.utils.FileUtil;
import com.bigtotoro.shuiyincamera.util.FileUtils;
import com.bigtotoro.shuiyincamera.util.ModelSingle;
import com.bigtotoro.shuiyincamera.util.VideoUtil;
import com.bigtotoro.shuiyincamera.video.VideoCropActivity;
import com.bigtotoro.shuiyincamera.video.view.CropImageView;
import com.bumptech.glide.Glide;
import com.umeng.analytics.MobclickAgent;

import java.io.File;

import io.microshow.rxffmpeg.RxFFmpegInvoke;
import io.microshow.rxffmpeg.RxFFmpegSubscriber;
import qiu.niorgai.StatusBarCompat;

import static com.bigtotoro.shuiyincamera.editimage.Constacts.EXTRA_OUTPUT;

/**
 * 图片去水印
 */
public class RemoveWaterMarkActivity extends AppCompatActivity implements View.OnClickListener {
    public static final String TAG = "image-remove-water";
    public static final String EXTRA_OUTPUT = "extra_output";

    private RelativeLayout iRoot;
    private FrameLayout frameLayout;
    private ImageView imageView;
    private CropImageView cropView;
    private int imageWidth, imageHeight;//
    private int rootWidth, rootHeight;//
    private String path;//从相册返回的原始图片存储地址
    private float scale;


    private String outPath;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_remove_water_mark);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.black));
        initView();
    }

    private void initView() {
        findViewById(R.id.back).setOnClickListener(this);
        findViewById(R.id.btn_save).setOnClickListener(this);

        path = getIntent().getStringExtra("path");//图片原始路径
        imageWidth = getIntent().getIntExtra("img-width", 0);
        imageHeight = getIntent().getIntExtra("img-height", 0);
        iRoot = findViewById(R.id.i_root);
        frameLayout = findViewById(R.id.frame);
        imageView = findViewById(R.id.img);
        cropView = findViewById(R.id.crop);



        imageView.postDelayed(new Runnable() {
            @Override
            public void run() {
                rootWidth = iRoot.getWidth();
                rootHeight = iRoot.getHeight();

                float xScale = (float) rootWidth / imageWidth;
                float yScale = (float) rootHeight / imageHeight;

                //For Center Crop use the Math.max to calculate the scale
                //float scale = Math.max(xScale, yScale);
                //For Center Inside use the Math.min scale.
                //I prefer Center Inside so I am using Math.min
                scale = Math.min(xScale, yScale);

                float scaledWidth = scale * imageWidth;
                float scaledHeight = scale * imageHeight;

                Log.i(TAG,"imageWidth=== "+imageWidth+" ,  imageHeight=== " + imageHeight);

                //Set the new size for the VideoView based on the dimensions of the video
                ViewGroup.LayoutParams layoutParams = frameLayout.getLayoutParams();
                layoutParams.width = (int) scaledWidth;
                layoutParams.height = (int) scaledHeight;
                frameLayout.setLayoutParams(layoutParams);
                frameLayout.invalidate(); //刷新界面

                if (path != null && path.lastIndexOf(".") > 0) {
                    Glide.with(RemoveWaterMarkActivity.this).load(new File(path)).into(imageView);
                }

                int xCenter = layoutParams.width/2;
                int yCenter = layoutParams.height/2;
                int initCropWidth = 400, intCropHeight = 200;
                //cropView.setCropRect(new RectF(xCenter-initCropWidth/2, yCenter-intCropHeight/2, xCenter+initCropWidth/2, yCenter+intCropHeight/2));
                cropView.setCropRect(new RectF(0, 0, layoutParams.width, layoutParams.height));


            }
        }, 100);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.btn_save:
                save();
                break;
        }
    }

    private ProgressDialog mProgressDialog;
    public static final int MSG_SUCCESS = 101;
    public static final int MSG_FAIL = 102;
    public static final int MSG_PROGRESS = 103;
    private static final int MSG_CANCLE = 104;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what==MSG_SUCCESS){
                Log.i(TAG,"去水印完成，跳转");
                Toast.makeText(RemoveWaterMarkActivity.this, "处理完成", Toast.LENGTH_SHORT).show();
                MyArt art = new MyArt();
                art.setPath(outPath);
                art.setCreate_time(System.currentTimeMillis()+"");
                art.setWidth(imageWidth);
                art.setHeight(imageHeight);
                art.setType(0);
                art.save();
                if(mProgressDialog.isShowing()){
                    mProgressDialog.dismiss();
                }
                Intent intent = new Intent(RemoveWaterMarkActivity.this, ShowMyArtsActivity.class);
                intent.putExtra(EXTRA_OUTPUT, art.getPath());
                intent.putExtra("create_time", art.getTrueCreateTime());
                intent.putExtra("width", imageHeight);
                intent.putExtra("height", imageWidth);
                intent.putExtra("type", "0");
                FileUtil.ablumUpdate(RemoveWaterMarkActivity.this, art.getPath(),0);//更新相册
                startActivity(intent);
                finish();

            }else if(msg.what==MSG_FAIL){
                Toast.makeText(RemoveWaterMarkActivity.this, "处理失败", Toast.LENGTH_SHORT).show();
                if(mProgressDialog.isShowing()){
                    mProgressDialog.dismiss();
                }
            }else if(msg.what==MSG_PROGRESS){
                float progress = msg.getData().getFloat("progress");
                mProgressDialog.setProgress((int) (progress));
            }else if(msg.what==MSG_CANCLE){
                float progress = msg.getData().getFloat("progress");
                mProgressDialog.setProgress((int) (progress));
            }
        }
    };


    private void save(){
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setMax(100);
        mProgressDialog.setCancelable(false);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setTitle("正在处理中");

        mProgressDialog.show();
        outPath = VideoUtil.VIDEO_SLIDE_IMAGE_DIR+"/"+System.currentTimeMillis()+".png";
        RectF rect = cropView.getCropRect();

        String cmd = String.format("ffmpeg -i %s -filter_complex delogo=x=%d:y=%d:w=%d:h=%d:show=0 %s", path,(int)(rect.left/scale), (int)(rect.top/scale), (int)(rect.width()/scale), (int)(rect.height()/scale), outPath);
        String[] commands = cmd.split(" ");
        try{
            RxFFmpegInvoke.getInstance().runCommandRxJava(commands).subscribe(new RxFFmpegSubscriber() {
                @Override
                public void onFinish() {
                    Log.i(TAG,"EpEditor.execCmd onSuccess");
                    mHandler.sendEmptyMessage(MSG_SUCCESS);
                }

                @Override
                public void onProgress(int progress, long progressTime) {
                    Log.i(TAG,"EpEditor.execCmd onProgress "+progress);
                    Message msg = new Message();
                    Bundle data = new Bundle();
                    data.putFloat("progress", progress);
                    msg.setData(data);
                    msg.what = MSG_PROGRESS;
                    mHandler.sendMessage(msg);
                }

                @Override
                public void onCancel() {
                    Log.i(TAG,"EpEditor.execCmd onFailure");
                    mHandler.sendEmptyMessage(MSG_CANCLE);
                }

                @Override
                public void onError(String message) {
                    Log.i(TAG,"EpEditor.execCmd onFailure");
                    mHandler.sendEmptyMessage(MSG_FAIL);
                }
            });
        }catch (Exception e){
            Log.e(TAG, e.getMessage());
            System.out.println(e);
            Toast.makeText(this, "保存出错", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("RemoveWaterMarkActivity");//统计页面
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("RemoveWaterMarkActivity");//统计页面
        MobclickAgent.onPause(this);
    }
}
